<template>
  <div>
    <el-button
      type="primary"
      @click="showAdd"
    >
      新建
    </el-button>

    <el-table
      v-loading="loading"
      u-mt-4
      :data="configList"
    >
      <el-table-column
        label="订单金额下限"
      >
        <template #default="{row}">
          {{ getPrice(row.priceFloor) }}
        </template>
      </el-table-column>

      <el-table-column
        label="订单金额上限"
      >
        <template #default="{row}">
          {{ getPrice(row.priceCeiling) }}
        </template>
      </el-table-column>

      <el-table-column
        label="运费"
        prop="freightFee"
      >
        <template #default="{row}">
          {{ getPrice(row.freightFee) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-text
            type="primary"
            u-cursor-pointer
            @click="showEdit(row)"
          >
            编辑
          </el-text>

          <el-text
            type="primary"
            u-cursor-pointer
            class="u-ml-2!"
            @click="remove(row)"
          >
            删除
          </el-text>
        </template>
      </el-table-column>
    </el-table>

    <div
      v-if="hasUnused"
      u="text-red flex items-center mt-4"
    >
      <el-icon u-mr-2>
        <WarningFilled />
      </el-icon>
      部分订单金额未配置运费，将按免运费计算
    </div>

    <Add
      ref="addRef"
      :ranges="ranges"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import Add from './add.vue'
import { WarningFilled } from '@element-plus/icons-vue'
const configList = ref([])

const addRef = ref()

const loading = ref(false)

const getPrice = price => {
  return has(price) ? price.toFixed(2) : undefined
}

const fetchConfig = async () => {
  loading.value = true
  const res = await http({
    url: http.adornUrl('/shop/freightConfig/page'),
    params: {
      current: current.value,
      size: size.value
    }
  })
  loading.value = false
  configList.value = res.data.records
  total.value = res.data.total
}
const { current, size, total } = usePagination(fetchConfig)

const ranges = computed(() => {
  return configList.value.reduce((res, item) => {
    const { priceFloor, priceCeiling } = item
    res.push([priceFloor, priceCeiling ?? Infinity])
    return res
  }, [])
})

size.value = 999
fetchConfig()

const showAdd = () => {
  const ranges = configList.value.reduce((res, item) => {
    const { priceFloor, priceCeiling } = item
    res.push([priceFloor, priceCeiling ?? Infinity])
    return res
  }, [])
  addRef.value.add(ranges, async (row) => {
    const { priceFloor, priceCeiling, freightFee } = row
    await http({
      url: http.adornUrl('/shop/freightConfig'),
      method: 'post',
      data: http.adornData({
        priceFloor,
        priceCeiling,
        freightFee,
        status: 0
      })
    })
    ElMessage.success('保存成功')
    fetchConfig()
  })
}

const showEdit = (row) => {
  const ranges = configList.value.reduce((res, item) => {
    const { priceFloor, priceCeiling } = item
    if (item.id !== row.id) {
      res.push([priceFloor, priceCeiling ?? Infinity])
    }
    return res
  }, [])
  addRef.value.edit(ranges, row, async (record) => {
    const { id, priceFloor, priceCeiling, freightFee } = record
    await http({
      url: http.adornUrl('/shop/freightConfig'),
      method: 'put',
      data: http.adornData({
        id,
        priceFloor,
        priceCeiling,
        freightFee
      })
    })
    ElMessage.success('修改成功')
    fetchConfig()
  })
}

const remove = async (row) => {
  await ElMessageBox.confirm('是否删除？', '提示', {
    type: 'warning'
  })
  await http({
    url: http.adornUrl(`/shop/freightConfig/${row.id}`),
    method: 'delete'
  })
  ElMessage.success('删除成功')
  fetchConfig()
}

const hasUnused = computed(() => {
  if (!configList.value.length) return false
  const ranges = configList.value.map(item => [item.priceFloor, item.priceCeiling ?? Infinity])
  ranges.sort((a, b) => a[0] - b[0])
  if (ranges[0][0] != 0) return true

  for (let i = 0; i < ranges.length - 1; i++) {
    const currentEnd = ranges[i][1]
    const nextStart = ranges[i + 1][0]

    if (nextStart > currentEnd + 0.01) {
      return true
    }
  }

  return false
})
</script>
